using System.Collections.Generic;
using System.Diagnostics;

namespace BizTalk.BuildGenerator
{
    /// <summary>
    /// Implements IComparer to sort a list of ApplicationResource objects based on their dependancy order
    /// </summary>
    public class ApplicationResourceComparer : IComparer<ApplicationResource>
    {
        #region IComparer<ApplicationResource> Members

        /// <summary>
        /// Compares application resources
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        public int Compare(ApplicationResource x, ApplicationResource y)
        {
            int result = 0;

            if (x != y)
            {
                bool myReference = DependsOn(x, y);
                if (myReference)
                    result = 1;
                //else
                //{
                //    bool yourReference = DependsOn(y, x);
                //    if (yourReference)
                //        result = -1;
                //}
            }
            Trace.WriteLine("");
            Trace.WriteLine("x = " + x.FullName);
            Trace.WriteLine("y = " + y.FullName);
            Trace.WriteLine("Result = " + result.ToString());
            Trace.WriteLine("");
            return result;
        }

        #endregion

        /// <summary>
        /// Recurses through the dependancies to find if one appembly depends on another in its reference tree
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        private static bool DependsOn(ApplicationResource x, ApplicationResource y)
        {            
            foreach (ApplicationResource dependant in x.DependantResources)
            {
                if (dependant.FullName == y.FullName)
                {
                    Trace.WriteLine("");
                    Trace.WriteLine(x.FullName);
                    Trace.WriteLine("Depends on");
                    Trace.WriteLine(dependant.FullName);
                    Trace.WriteLine("");
                    return true;
                }

                return DependsOn(dependant, y);
            }

            return false;
        }
    }
}